from django.db import models
from annoying.functions import get_object_or_None
from django.contrib.contenttypes.models import ContentType

import core
from core.models import User
from core.models.auth.providers import Vkontakte

class VkontakteCredential(models.Model):
    vk_id = models.CharField(max_length=255, unique=True)

    class Meta:
        app_label = core.APP_LABEL

    class AlreadyExists(Exception):
        pass

    def __unicode__(self):
        return self.vk_id
    
    def authenticate(self):
    
        credential = get_object_or_None(VkontakteCredential, vk_id=self.vk_id)
    
        if credential is not None:
            content_type = ContentType.objects.get_for_model(credential)
            return User.objects.get(auth__content_type=content_type,
                                    auth__credential_id=credential.id)
    
        return None
    
    
    def register(self):
    
        if VkontakteCredential.objects.filter(vk_id=self.vk_id).exists():
            raise self.AlreadyExists()
    
        credential = VkontakteCredential.objects.create(vk_id=self.vk_id)
    
        user = User.objects.create()
        user.name = 'user{0}'.format(user.id)
        user.save()
        user.auth_set.create(provider=Vkontakte, credential=credential)
    
        return user

